import React, { createContext, useContext, useState, ReactNode } from 'react';
import { useAuth } from '../auth/AuthContext';

interface PointsTransaction {
  id: string;
  userId: string;
  type: 'upload' | 'download' | 'share' | 'bonus';
  points: number;
  description: string;
  createdAt: string;
}

interface PointsContextType {
  transactions: PointsTransaction[];
  loading: boolean;
  calculateLevel: (points: number) => number;
  calculateShareRatio: (points: number) => number;
  addPoints: (type: PointsTransaction['type'], points: number, description: string) => Promise<void>;
  getTransactionHistory: () => Promise<void>;
}

const PointsContext = createContext<PointsContextType | null>(null);

export const usePoints = () => {
  const context = useContext(PointsContext);
  if (!context) {
    throw new Error('usePoints must be used within a PointsProvider');
  }
  return context;
};

interface PointsProviderProps {
  children: ReactNode;
}

export const PointsProvider: React.FC<PointsProviderProps> = ({ children }) => {
  const [transactions, setTransactions] = useState<PointsTransaction[]>([]);
  const [loading, setLoading] = useState(false);
  const { user } = useAuth();

  // 根据积分计算用户等级
  const calculateLevel = (points: number): number => {
    if (points < 100) return 1;
    if (points < 500) return 2;
    if (points < 2000) return 3;
    if (points < 5000) return 4;
    return 5;
  };

  // 根据积分计算分享率
  const calculateShareRatio = (points: number): number => {
    const level = calculateLevel(points);
    switch (level) {
      case 1: return 1.0;
      case 2: return 1.2;
      case 3: return 1.5;
      case 4: return 2.0;
      case 5: return 3.0;
      default: return 1.0;
    }
  };

  // 添加积分
  const addPoints = async (type: PointsTransaction['type'], points: number, description: string) => {
    if (!user) return;

    try {
      setLoading(true);
      const response = await fetch('/api/points/add', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          userId: user.id,
          type,
          points,
          description,
        }),
      });

      if (!response.ok) {
        throw new Error('添加积分失败');
      }

      const newTransaction = await response.json();
      setTransactions(prev => [...prev, newTransaction]);
    } catch (error) {
      console.error('积分添加错误:', error);
      throw error;
    } finally {
      setLoading(false);
    }
  };

  // 获取交易历史
  const getTransactionHistory = async () => {
    if (!user) return;

    try {
      setLoading(true);
      const response = await fetch(`/api/points/history/${user.id}`);

      if (!response.ok) {
        throw new Error('获取交易历史失败');
      }

      const history = await response.json();
      setTransactions(history);
    } catch (error) {
      console.error('获取交易历史错误:', error);
      throw error;
    } finally {
      setLoading(false);
    }
  };

  return (
    <PointsContext.Provider value={{
      transactions,
      loading,
      calculateLevel,
      calculateShareRatio,
      addPoints,
      getTransactionHistory,
    }}>
      {children}
    </PointsContext.Provider>
  );
};